import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image } from '@tarojs/components'
import { connect } from 'react-redux'
import { getMiniShareImage } from '@/api/distribution'
import './index.scss'
const invite_share_icon = 'https://static3.jekunauto.com/img/others/invite_share_icon.png'
const save_success_icon = 'https://static3.jekunauto.com/img/others/checked.png'
interface State {
  imgList: any,
  poster: any,
  tips: boolean,
  type: any,
  openVisable: any
}
@connect<any>(({ location, car }) => ({ storeInfo: location.storeLocation, car: car.carInfo.currentCar }))
class InvitePoster extends Component<any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      type: '',
      tips: false,
      imgList: [],
      openVisable: false,
      poster:''
    }
  }
  state: State
  componentDidMount() {
    const { shareId, userMobile,superiorMobile='' } = this.$instance.router.params
		console.log('this.$instance.router.params',this.$instance.router.params)
    this.getDistributionPoster({
			shareId,
			userMobile,
			superiorMobile
		})
  }
  UNSAFE_componentWillReceiveProps() {
  }
  private car: ICar | {} = {}

  /**
  * 获取分享海报
  **/
  getDistributionPoster({ shareId, userMobile ,superiorMobile}) {
		Taro.showLoading({
			title: '生成海报中...',
			mask: true
    })

    getMiniShareImage({
      shareId,
      userMobile,
			superiorMobile
    }).then(res => {
			let poster = res?.data?.data?.shareWechatImage
			this.setState({
				poster
			},()=>{
				console.log('成功了')
				console.log(res)
				Taro.hideLoading()
			})
    })
  }


  /**
  * 下载图片
  **/
  downloadImg(shareImg) {
    Taro.getSetting({
      success: res => {
        Taro.authorize({
          scope: 'scope.writePhotosAlbum',
          success: res => {
            console.log('授权成功');
            let imgUrl = shareImg;
            console.log(imgUrl);
            Taro.downloadFile({  //下载文件资源到本地，客户端直接发起一个HTTP GET 请求，返回文件的本地临时路径
              url: imgUrl,
              success: res => {
                Taro.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath, //返回的临时文件路径，下载后的文件会存储到一个临时文件
                  success: res => {
                    Taro.showToast({
                      title: '成功保存到相册',
                      icon: 'success'
                    })
                  }
                })
              }
            })
          },
          fail: err => {
            this.setState({
              openVisable: true
            })
          }
        })
      }
    })
  }

	/**
  * 保存图片
  **/
  openSaveImg() {
    let _this = this
    Taro.openSetting().then(resp => {
      const status = resp.authSetting['scope.writePhotosAlbum']
      if (status) {
        Taro.showToast({
          title: '开启成功',
          icon: 'success'
        })
        _this.closeOpenVisable()
      }
    })
  }

  /**
   * 下载素材
   */
  saveImg() {
    this.downloadImg(this.state.poster)
  }


  closeOpenVisable() {
    this.setState({
      openVisable: false
    })
  }


  render() {
    const {  openVisable,poster } = this.state
    return (
      <View className="container">
        <Image className='poster' src={poster}></Image>

        <View className="footer">
          <View className='title'>分享方式</View>
          <Image className='invite_share_icon' src={invite_share_icon}></Image>
					{

					}
          <View className='save_tip'>
            <Image src={save_success_icon}></Image>
            素材已保存到相册</View>
          <View className="btn" onClick={() => this.saveImg()}>
            下载到手机
          </View>
        </View>
        {
          openVisable ? (
            <View className="dialog-wrap" >
              <View className="dialog-bg" onClick={this.closeOpenVisable}></View>
              <View className="dialog-mask">
                <View className="dialog-tips">请先开启保存相册的权限</View>
                <View className="open-btn" onClick={this.openSaveImg}>开启权限</View>
              </View>
            </View>
          ) : null
        }

      </View>
    )
  }
}
export default InvitePoster
